<template>
  <div>

    <el-form :inline="true" class="queryForm" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()"
             @submit.native.prevent>
      <el-form-item prop="type" label="关键字:">
        <div style="width:230px">
          <el-input size="small" v-model="searchForm.type" placeholder="请输入关键字查询" clearable></el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button class="but-container" type="primary" @click="refreshList()" size="small">查询</el-button>
        <el-button @click="resetSearch()" size="small">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button v-if="hasPermission('sys:dict:add')" type="primary" size="small" @click="add()">新增</el-button>
      <section class="right-but" style="display:flex">
        <el-button type="text" style="margin-right:-13px" @click="refreshList()">
          <img style="width:44px;height:36px;" src="~@/assets/img/shuaxin.png">
        </el-button>
        <PopoverBut :checkedProps="checkedProps" :options="options" @getCheckeds="handlerCloumn"></PopoverBut>
      </section>
      <!-- <el-button v-if="hasPermission('sys:dict:edit')" type="warning" size="small" @click="edit()"
      :disabled="dataListSelections.length !== 1" plain>修改</el-button>
      <el-button v-if="hasPermission('sys:dict:del')" type="danger"   size="small" @click="del()"
                :disabled="dataListSelections.length <= 0" plain>删除
      </el-button> -->
      <!-- <el-button-group class="pull-right">

        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            type="default"
            size="small"
            icon="el-icon-refresh"
            @click="refreshList">
          </el-button>
        </el-tooltip>
      </el-button-group> -->
    </el-row>
    <el-table
        :data="dataList"
        v-loading="loading"
        border
        size="medium"
        @selection-change="selectionChangeHandle"
        @sort-change="sortChangeHandle"
        class="table table-wrapper listTable-wrapper">
      <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="60">
      </el-table-column>
      <el-table-column
          prop="type"
          sortable="custom"
          label="类型">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" v-if="hasPermission('sys:dict:edit')" @click="edit(scope.row.id)">
            {{ scope.row.type }}
          </el-link>
          <el-link type="primary" :underline="false" v-else-if="hasPermission('sys:dict:view')"
                   @click="view(scope.row.id)">{{ scope.row.type }}
          </el-link>
          <span v-else>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="sort"
          label="排序">
      </el-table-column>
      <el-table-column prop="type" label="字典类型">
        <!--     字段中没有type值，$dictUtils.getDictLabel("type", scope.row.type, "") 条件不存在， 显示--        -->
        <template slot-scope="scope">
          {{ $dictUtils.getDictLabel("type", scope.row.type, "--") }}
          <!--              &#45;&#45;-->
        </template>
      </el-table-column>
      <el-table-column prop="tenantAutho" label="租户权限">
        <template slot-scope="scope">
          {{ $dictUtils.getDictLabel("tenant_autho", scope.row.tenantAutho, "") }}
        </template>
      </el-table-column>
      <el-table-column
          prop="description"
          label="描述">
      </el-table-column>
      <el-table-column prop="state" label="状态" align="left" header-align="left" width="130px">
        <template slot-scope="scope">
          <!-- <el-switch
            v-model="scope.row.state"
            :inactive-value="Number($dictUtils.getDictList('state')[1].value)"
            :active-value="Number($dictUtils.getDictList('state')[0].value)"
            @change="editState($event,scope.row)"
          >
          </el-switch> -->
          <div style="text-align: center;">
            <section class="activate-state" v-if="scope.row.state===1">
              <i></i>
               {{ $dictUtils.getDictLabel("state", scope.row.state, "") }}
            </section>
            <section class="inactive-state" v-else>
              <i></i>
              {{ $dictUtils.getDictLabel("state", scope.row.state, "") }}
            </section>

          </div>

        </template>
      </el-table-column>
      <span v-for="(item,index) in checkedProps" :key="index">
             <el-table-column prop="createBy.loginName" :label="item" v-if="item==='创建人'" min-width="120">
                <template slot-scope="scope">
                  <span v-if="scope.row.createBy && scope.row.createBy.loginName">
                       {{ scope.row.createBy.loginName | noValue }}
                  </span>
                  <span v-else>--</span>
              </template>
             </el-table-column>
             <el-table-column prop="createDate" :label="item" v-if="item==='创建时间'" min-width="180"></el-table-column>
             <el-table-column prop="updateBy.loginName" :label="item" v-if="item==='上次操作人'" min-width="140">
                <template slot-scope="scope">
                  <span v-if="scope.row.updateBy && scope.row.updateBy.loginName">
                     {{ scope.row.updateBy.loginName | noValue }}
                  </span>
                  <span v-else>--</span>
              </template>
             </el-table-column>
             <el-table-column prop="updateDate" :label="item" v-if="item==='上次操作时间'" min-width="180"
                              sortable="update_date"></el-table-column>
          </span>
      <el-table-column
          fixed="right"
          width="440"
          label="操作">
        <template slot-scope="scope">
          <template v-for="item in $dictUtils.getDictList('state')">
            <el-button type="text"
                       v-if="!((scope.row.state===-1&& item.value==='0')||item.value==scope.row.state)&&item.label!=='未启用'"
                       @click="editState(item.value,scope.row)"
                       :disabled="(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state"
            >{{ item.label }}
            </el-button>
          </template>
          <el-button v-if="hasPermission('sys:dict:edit')&& scope.row.tenantAutho===2" type="text" size="small"
                     @click="edit(scope.row.id)">修改
          </el-button>
          <el-button v-if="hasPermission('sys:dict:del')" type="text" size="small" @click="del(scope.row.id)">
            删除
          </el-button>
          <el-button v-if="hasPermission('sys:dict:edit')" type="text" size="small" @click="showRight(scope.row)">
            管理键值
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <dict-type-form ref="dictTypeForm" @refreshDataList="refreshList"></dict-type-form>
    <el-drawer
        size="700px"
        :title="`数据字典值列表，所属类型: ${this.dictTypeTitle}`"
        :visible.sync="rightVisible"
        direction="rtl">
      <dict-value-list :dict-type-title="dictTypeTitle" ref="dictValueList" @closeRight="closeRight"></dict-value-list>
    </el-drawer>

  </div>
</template>

<script>
import DictTypeForm from './DictTypeForm'
import DictValueList from './DictValueList'
import {typemodifyState} from '@/api/dict.js'
import PopoverBut from '@/components/button/popoverBut'

const options1 = []
export default {
  data () {
    return {
      searchForm: {
        type: ''
      },
      dataList: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      orderBy: '',
      dataListSelections: [],
      checkedProps: options1,
      options: [
        {
          label: '创建人',
          key: 'createBy.loginName'
        },
        {
          label: '创建时间',
          key: 'createDate'
        },
        {
          label: '上次操作人',
          key: 'updateBy.loginName'
        },
        {
          label: '上次操作时间',
          key: 'updateDate'
        }],
      isSearchCollapse: false,
      dictTypeTitle: '',
      rightVisible: false,
      loading: false,
      id: ''
    }
  },
  components: {
    DictTypeForm,
    DictValueList,
    PopoverBut
  },
  activated () {
    this.refreshList()
  },
  methods: {
    // 获取数据列表
    refreshList () {
      this.loading = true
      this.$http({
        url: '/sys/dict/type/list',
        method: 'get',
        params: {
          'pageNo': this.pageNo,
          'pageSize': this.pageSize,
          'type': this.searchForm.type,
          'orderBy': this.orderBy
        }
      }).then(({data}) => {
        if (data && data.success) {
          debugger
          // 只展示运营端为"可见不可编辑"和"可编辑的字段"
          let dictList = JSON.parse(sessionStorage.getItem('dictList') || '[]')
          let dicts = dictList.tenant_autho
          let tenantData = dicts.filter(item => {
            return item.label === '不可见'
          })[0]           // 不可见的字典id
          let list = data.page.list
          if (tenantData.length) {
            list.map(item => {
              return item.tenantAutho != tenantData.value
            })
          }
          this.dataList = list
          this.total = data.page.count
          this.loading = false
        }
      })
    },
    // 状态修改
    editState (event, row) {
      console.log(row)
      this.$confirm('您是否要' + this.$dictUtils.getDictLabel('state', event, '') + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        typemodifyState(
            {
              id: row.id,
              state: event
            }
        ).then(res => {
          console.log(res)
          if (res.data.code === '200') {
            this.refreshList()
            this.$message({
              type: 'success',
              message: '状态修改成功'
            })
          }
        })
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageNo = 1
      this.refreshList()
    },
    // 是否显示某列数据
    handlerCloumn (e) {
      this.checkedProps = e
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageNo = val
      this.refreshList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 排序
    sortChangeHandle (obj) {
      if (obj.order === 'ascending') {
        this.orderBy = obj.prop + ' asc'
      } else {
        this.orderBy = obj.prop + ' desc'
      }
      this.refreshList()
    },
    // 新增
    add () {
      this.$refs.dictTypeForm.init('add', '')
    },
    // 修改
    edit (id) {
      id = id || this.dataListSelections.map(item => {
        return item.id
      })[0]
      this.$refs.dictTypeForm.init('edit', id)
    },
    // 查看
    view (id) {
      this.$refs.dictTypeForm.init('view', id)
    },
    // 删除
    del (id) {
      let ids = id || this.dataListSelections.map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/sys/dict/delete',
          method: 'delete',
          params: {'ids': ids}
        }).then(({data}) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.refreshList()
            this.$dictUtils.refreshDictList()
          }
        })
      })
    },
    resetSearch () {
      this.$refs.searchForm.resetFields()
      this.refreshList()
    },
    showRight (row) {
      console.log(row)
      this.rightVisible = true
      this.$nextTick(() => {
        this.$refs.dictValueList.refreshList(row.id)
        this.dictTypeTitle = row.type
      })
    },
    closeRight () {
      this.rightVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.queryForm {
  position: relative;

  .but-container {
    top: 20px;
    margin-left: 40px;
  }

}

</style>
